<template>
    <div class="backpack-container">
      <el-card class="backpack-header">
        <div class="header-content">
          <h1>我的宝藏背包</h1>
          <div class="player-info">
            <el-avatar :size="50" :src="playerInfo.avatar"></el-avatar>
            <div class="player-details">
              <h2>{{ playerInfo.name }}</h2>
              <div class="player-stats">
                <el-tag type="success">魅力值：{{ playerInfo.charm }}</el-tag>
                <el-tag type="warning">
                  <el-icon><Coin /></el-icon>
                  {{ playerInfo.coins }} TERS
                </el-tag>
              </div>
            </div>
          </div>
        </div>
      </el-card>
  
      <div class="backpack-control">
        <el-input
          v-model="searchQuery"
          placeholder="搜索宝藏..."
          class="search-input"
          prefix-icon="Search"
        ></el-input>
        <el-select v-model="rarityFilter" placeholder="稀有度" class="filter-select">
          <el-option v-for="item in rarityOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
        <el-select v-model="sortOption" placeholder="排序方式" class="filter-select">
          <el-option v-for="item in sortOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
        <el-switch
          v-model="gridView"
          active-text="网格视图"
          inactive-text="列表视图"
          class="view-toggle"
        ></el-switch>
      </div>
  
      <!-- 网格视图 -->
      <div v-if="gridView" class="nft-grid">
        <el-card
          v-for="nft in filteredNFTs"
          :key="nft.id"
          class="nft-card"
          :class="'rarity-' + nft.rarity.toLowerCase()"
          @click="showNFTDetails(nft)"
        >
          <div class="nft-image-container">
            <el-image :src="nft.image" fit="scale-down" class="nft-image">
              <template #error>
                <div class="image-error">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
            <el-tag class="rarity-tag" :type="getRarityType(nft.rarity)">{{ nft.rarity }}</el-tag>
          </div>
          <div class="nft-info">
            <h3 class="nft-name">{{ nft.name }}</h3>
            <p class="nft-description">{{ truncateText(nft.description, 60) }}</p>
            <div class="nft-footer">
              <span class="nft-id">#{{ nft.tokenId }}</span>
              <el-tooltip content="在区块链浏览器中查看" placement="top">
                <el-button 
                  link
                  @click.stop="viewOnBlockchain(nft)"
                >
                  <el-icon><Link /></el-icon>
                </el-button>
              </el-tooltip>
            </div>
          </div>
        </el-card>
      </div>
  
      <!-- 列表视图 -->
      <el-table
        v-else
        :data="filteredNFTs"
        style="width: 100%"
        @row-click="showNFTDetails"
      >
        <el-table-column width="80">
          <template #default="scope">
            <el-image :src="scope.row.image" fit="cover" style="width: 60px; height: 60px; border-radius: 8px;"></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="名称"></el-table-column>
        <el-table-column prop="description" label="描述">
          <template #default="scope">
            {{ truncateText(scope.row.description, 80) }}
          </template>
        </el-table-column>
        <el-table-column prop="rarity" label="稀有度">
          <template #default="scope">
            <el-tag :type="getRarityType(scope.row.rarity)">{{ scope.row.rarity }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="tokenId" label="ID" width="80"></el-table-column>
        <el-table-column label="操作" width="100">
          <template #default="scope">
            <el-button 
              link
              size="small" 
              @click.stop="showNFTDetails(scope.row)"
            >
              <el-icon><View /></el-icon>
            </el-button>
            <el-button 
              link
              type="info"
              size="small" 
              @click.stop="viewOnBlockchain(scope.row)"
            >
              <el-icon><Link /></el-icon>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <!-- 加载更多 -->
      <div class="load-more">
        <el-button type="primary" :loading="loading" @click="loadMore">加载更多宝藏</el-button>
      </div>
  
      <!-- NFT详情弹窗 -->
      <el-dialog v-model="detailsVisible" title="宝藏详情" width="50%" center destroy-on-close>
        <div v-if="selectedNFT" class="nft-details">
          <div class="details-header">
            <el-image :src="selectedNFT.image" fit="cover" class="details-image"></el-image>
            <div class="details-info">
              <h2>{{ selectedNFT.name }}</h2>
              <el-tag class="details-rarity" :type="getRarityType(selectedNFT.rarity)">{{ selectedNFT.rarity }}</el-tag>
              <p class="details-description">{{ selectedNFT.description }}</p>
              <div class="details-meta">
                <div class="meta-item">
                  <span class="meta-label">收集日期:</span>
                  <span>{{ formatDate(selectedNFT.collectedAt) }}</span>
                </div>
                <div class="meta-item">
                  <span class="meta-label">代币ID:</span>
                  <span>#{{ selectedNFT.tokenId }}</span>
                </div>
                <div class="meta-item">
                  <span class="meta-label">区块高度:</span>
                  <span>{{ selectedNFT.blockNumber }}</span>
                </div>
              </div>
            </div>
          </div>
          
          <el-divider content-position="center">属性</el-divider>
          
          <div class="details-attributes">
            <el-card v-for="attr in selectedNFT.attributes" :key="attr.trait_type" class="attribute-card">
              <template #header>
                <div class="attribute-header">{{ attr.trait_type }}</div>
              </template>
              <div class="attribute-value">{{ attr.value }}</div>
              <!-- <div class="attribute-rarity">稀有度 {{ attr.rarity_percentage }}%</div> -->
            </el-card>
          </div>
          
          <el-divider content-position="center">操作</el-divider>
          
          <div class="details-actions">
            <template v-if="!selectedNFT.isUnlocked">
              <el-button type="primary" @click="unlockNFT(selectedNFT)">解锁宝藏</el-button>
            </template>
            <template v-else>
              <el-button type="success" @click="transferNFT(selectedNFT)">转赠</el-button>
              <el-button type="warning" @click="sellNFT(selectedNFT)">出售</el-button>
            </template>
            <el-button @click="viewOnBlockchain(selectedNFT)">在区块链浏览器中查看</el-button>
          </div>
        </div>
      </el-dialog>
  
      <!-- 上架对话框 -->
      <el-dialog
        v-model="listDialog.visible"
        title="上架宝藏"
        width="400px"
        center
      >
        <div class="list-form">
          <el-form :model="listDialog.form" label-width="80px">
            <el-form-item label="售价">
              <el-input-number 
                v-model="listDialog.form.price"
                :min="1"
                :precision="0"
                :step="1"
                controls-position="right"
              />
              <span class="price-unit">TRES</span>
            </el-form-item>
          </el-form>
        </div>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="listDialog.visible = false">取消</el-button>
            <el-button type="primary" @click="confirmList" :loading="listDialog.loading">
              确认上架
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script setup>
  import { ref, computed, onMounted } from 'vue';
  import { Search, Picture, Link, View, Coin } from '@element-plus/icons-vue';
  import { useWalletStore } from '../stores/walletStore';
  import { ethers } from 'ethers';
  import "../styles/InventoryView.css"
  import { randomRarity, convertToAttributeArray, generateAvatar, generateRandomAttributes, generateTreasureDescription } from '../interact/Asistant';
 
  import { ElMessage } from 'element-plus';
  import { useRouter } from 'vue-router';
  const walletStore = useWalletStore();
  let balance = "0"; // 默认余额为0
  const router = useRouter();

  // 格式化数字的函数
  const formatNumber = (num) => {
    return new Intl.NumberFormat('zh-CN').format(num);
  };
  // 使用立即执行的异步函数获取余额
  (async () => {
    try {
      const rawBalance = await walletStore.tokenContract.balanceOf(walletStore.walletAddress);
      // 获取玩家魅力值
      const charm = await walletStore.contract.getPlayerCharm(walletStore.walletAddress);
      // 直接使用原始值，添加格式化
      balance = formatNumber(rawBalance.toString());
      console.log("用户 TERS 余额为", balance);
      console.log("用户魅力值为", charm);
      // 更新玩家信息中的金币数量
      playerInfo.value.coins = balance;
      playerInfo.value.charm = charm;
    } catch (error) {
      console.error("获取余额失败:", error);
    }
  })();

  // 获取钱包地址后四位
  const walletAddress = walletStore.walletAddress || "";
  const lastFourChars = walletAddress.length >= 4 
    ? walletAddress.slice(-4) 
    : walletAddress;

  // 玩家信息
  const playerInfo = ref({
    name: `宝藏猎人 #${lastFourChars}`, // 使用钱包地址后四位作为玩家标识
    level: 42,
    coins: balance, // 初始为0，稍后会被更新
    avatar: generateAvatar(walletAddress) // 使用钱包地址生成头像
  });
  
  // NFT列表
  const nfts = ref([]);
  const loading = ref(false);
  const page = ref(1);
  const pageSize = ref(12);
  
  // 筛选和排序
  const searchQuery = ref('');
  const rarityFilter = ref('');
  const sortOption = ref('recent');
  const gridView = ref(true);
  
  // 弹窗控制
  const detailsVisible = ref(false);
  const selectedNFT = ref(null);
  
  // 选项列表
  const rarityOptions = [
    { value: '', label: '全部稀有度' },
    { value: 'Common', label: '普通' },
    { value: 'Rare', label: '稀有' },
    { value: 'Epic', label: '史诗' },
    { value: 'Legendary', label: '传说' }
  ];
  
  const sortOptions = [
    { value: 'recent', label: '最近获得' },
    { value: 'oldest', label: '最早获得' },
    { value: 'rarity', label: '稀有度' },
    { value: 'name', label: '名称' }
  ];
  
  // 过滤NFT列表
  const filteredNFTs = computed(() => {
    let result = [...nfts.value];
    
    // 搜索过滤
    if (searchQuery.value) {
      const query = searchQuery.value.toLowerCase();
      result = result.filter(nft => 
        nft.name.toLowerCase().includes(query) || 
        nft.description.toLowerCase().includes(query)
      );
    }
    
    // 稀有度过滤
    if (rarityFilter.value) {
      result = result.filter(nft => nft.rarity === rarityFilter.value);
    }
    
    // 排序
    switch (sortOption.value) {
      case 'recent':
        result.sort((a, b) => new Date(b.collectedAt) - new Date(a.collectedAt));
        break;
      case 'oldest':
        result.sort((a, b) => new Date(a.collectedAt) - new Date(b.collectedAt));
        break;
      case 'rarity':
        const rarityOrder = { 'Common': 1, 'Uncommon': 2, 'Rare': 3, 'Epic': 4, 'Legendary': 5 };
        result.sort((a, b) => rarityOrder[b.rarity] - rarityOrder[a.rarity]);
        break;
      case 'name':
        result.sort((a, b) => a.name.localeCompare(b.name));
        break;
    }
    
    return result;
  });
  
  // 获取NFT数据
  const fetchNFTs = async () => {
    loading.value = true;
    try {
      // 获取玩家拥有的nft数量
      const nftCount = await walletStore.contract.balanceOf(walletStore.walletAddress);
      console.log("玩家拥有的nft数量为", nftCount);
      
      // 计算当前分页应获取的NFT索引范围
      const startIndex = (page.value - 1) * pageSize.value;
      const endIndex = Math.min(startIndex + pageSize.value, Number(nftCount));
      
      // 存储本次获取的NFT数据
      const newNFTs = [];
      
      // 获取玩家的nft tokenID和tokenUri
      for (let i = startIndex; i < endIndex; i++) {
        try {
          // 获取tokenId
          const tokenId = await walletStore.contract.tokenOfOwnerByIndex(walletStore.walletAddress, i);
          console.log(`获取到第${i}个NFT，tokenId为:`, tokenId.toString());
          
          // 获取元数据URI
          const uri = await walletStore.contract.tokenURI(tokenId);
          console.log(`NFT #${tokenId} 的URI为:`, uri);
          
          // 获取nft的元数据
          const response = await fetch(uri);
          
          if (!response.ok) {
            console.error(`获取NFT元数据失败: ${response.status} ${response.statusText}`);
            continue;
          }
          
          const metadata = await response.json();
          console.log(`NFT #${tokenId} 的元数据为:`, metadata);
          const rarity = metadata.attributes[0].value;
          console.log("NFT #${tokenId} 的稀有度为:", rarity);
          // 构建NFT对象
          const nft = {
            id: i + 1, // 界面展示用的ID
            tokenId: tokenId.toString(),
            name: `数字宝藏 #${rarity} ${tokenId}`,
            description: generateTreasureDescription(rarity || randomRarity(), tokenId),
            image: metadata.image ? `https://pink-obliged-bat-235.mypinata.cloud/ipfs/${metadata.image.slice(7)}` : `https://via.placeholder.com/300/30${i % 10}${Math.floor(i/10) % 10}`,
            rarity: rarity || randomRarity(), // 如果元数据中没有稀有度，随机生成一个
            collectedAt: metadata.created_at || new Date().toISOString(),
            blockNumber: metadata.block_number || 15000000 + i,
            attributes: metadata.attributes ? convertToAttributeArray(metadata.attributes) : generateRandomAttributes(),
            isUnlocked: walletStore.contract.isSolved(tokenId),
          };
          
          newNFTs.push(nft);

        } catch (error) {
          console.error(`处理NFT索引${i}时出错:`, error);
          // 继续处理下一个NFT
        }
      }
      
      // 将获取到的NFT数据添加到现有列表中
      nfts.value = [...nfts.value, ...newNFTs];
      
      // 增加页码，为下次加载做准备
      page.value++;
      
      // 如果没有获取到任何NFT但仍在尝试加载，可能是已经加载完所有NFT
      if (newNFTs.length === 0 && Number(nftCount) > 0) {
        console.log("已加载所有NFT或获取NFT失败");
      }
    } catch (error) {
      console.error('获取NFT数据失败:', error);
      // 出错时可以向用户显示提示
      ElMessage.error('获取NFT数据失败，请稍后再试');
    } finally {
      loading.value = false;
    }
  };
  
  
  
  
  
  
  
  // 加载更多NFT
  const loadMore = () => {
    fetchNFTs();
  };
  
 
  
  // 显示NFT详情
  const showNFTDetails = (nft) => {
    selectedNFT.value = nft;
    console.log("nft详情：", selectedNFT.value);
    detailsVisible.value = true;
  };
  
  // 装备NFT
  const equipNFT = (nft) => {
    // 实现装备逻辑
    console.log('装备NFT:', nft);
  };
  
  // 转移NFT
  const transferNFT = (nft) => {
    // 实现转移逻辑
    console.log('转移NFT:', nft);
  };
  
  // 上架对话框状态
  const listDialog = ref({
    visible: false,
    form: {
      price: 1
    },
    loading: false,
    nft: null
  });

  // 出售 NFT
  const sellNFT = (nft) => {
    listDialog.value.nft = nft;
    console.log("出售的NFT为", nft);
    listDialog.value.visible = true;
  };
  
  // 确认上架
  const confirmList = async () => {
    const { nft, form } = listDialog.value;
    listDialog.value.loading = true;
    
    try {
      const price = form.price;
      const tx = await walletStore.marketContract.listTreasureForSale(nft.tokenId, price);
      await tx.wait();
      // 卖家首先批准市场合约操作NFT
      const approveNFT = await walletStore.contract.setApprovalForAll(
        walletStore.marketContract.address, 
        true
      );
      console.log("批准市场合约操作NFT", approveNFT);
      await approveNFT.wait();// 
      ElMessage.success('上架成功！');
      listDialog.value.visible = false;
        
      // 可以选择跳转到市场页面
      router.push('/market');
    } catch (error) {
      console.error('上架失败:', error);
      ElMessage.error('上架失败：' + error.message);
    } finally {
      listDialog.value.loading = false;
    }
  };
  
  // 在区块链浏览器中查看
  const viewOnBlockchain = (nft) => {
    // 实现查看逻辑
    window.open(`https://etherscan.io/token/${nft.tokenId}`, '_blank');
  };
  
  // 获取稀有度对应的样式类型
  const getRarityType = (rarity) => {
    switch (rarity) {
      case 'Common': return 'success';
      case 'Rare': return 'warning';
      case 'Epic': return 'danger';
      case 'Legendary': return 'primary';
      default: return 'info';
    }
  };
  
  // 格式化日期
  const formatDate = (dateString) => {
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN', { year: 'numeric', month: 'long', day: 'numeric' });
  };
  
  // 文本截断
  const truncateText = (text, maxLength) => {
    if (text.length <= maxLength) return text;
    return text.substring(0, maxLength) + '...';
  };
  
  // 组件挂载时获取数据
  onMounted(() => {
    fetchNFTs();
  });
  </script>

<style scoped>
.list-form {
  padding: 20px;
}

.price-unit {
  margin-left: 10px;
  color: #909399;
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 20px;
  padding-top: 20px;
}

.player-stats .el-tag {
  margin-right: 8px;
  padding: 0 12px;
  height: 28px;
  line-height: 26px;
}

.player-stats .el-icon {
  margin-right: 4px;
  vertical-align: middle;
}
</style>
